package com.zdzx.controller.admin.content;

import java.time.LocalDateTime;
import java.util.Collections;
import java.util.Comparator;
import java.util.List;

import javax.servlet.http.HttpServletRequest;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.util.StringUtils;
import org.springframework.web.bind.annotation.DeleteMapping;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.PutMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.zdzx.base.common.util.RedisUtil;
import com.zdzx.base.common.util.UserInfoUtil;
import com.zdzx.common.result.PageInfo;
import com.zdzx.common.result.PageUtil;
import com.zdzx.common.result.Result;
import com.zdzx.common.result.ResultCode;
import com.zdzx.common.result.ResultUtil;
import com.zdzx.mapper.CourseMapper;
import com.zdzx.mapper.CourseTypeMapper;
import com.zdzx.mapper.SystemConfigMapper;
import com.zdzx.model.constant.SystemConfig;
import com.zdzx.model.dic.SystemConfigType;
import com.zdzx.model.service.base.result.UserInfo;
import com.zdzx.model.service.content.vo.Course;
import com.zdzx.model.service.content.vo.CourseType;
import com.zdzx.service.OSSService;

import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import io.swagger.annotations.ApiParam;

@Api(tags = "课程")
@RestController
@RequestMapping("/admin")
public class CourseController {


	@Autowired
	private CourseMapper courseMapper;
	@Autowired
	private CourseTypeMapper courseTypeMapper;
	@Autowired
	private SystemConfigMapper systemConfigMapper;
	@Autowired
	private OSSService ossService;
	@Autowired
	private RedisUtil redisUtil;

	
	@ApiOperation(value = "获取列表", notes = "")
	@GetMapping("/course")
	public Result<PageInfo<Course>> list(
			@ApiParam("") @RequestParam(value = "pageNum", required = false) Integer pageNum,
			@ApiParam("") @RequestParam(value = "pageSize", required = false) Integer pageSize,
			@ApiParam("") @RequestParam(value = "title", required = false) String title,
			@ApiParam("1免费 0收费") @RequestParam(value = "free", required = false) String free,
			@ApiParam("0视频 1文章 2直播") @RequestParam(value = "type", required = false) String type,
			@ApiParam("课程分类") @RequestParam(value = "courseType", required = false) String courseType,
			@ApiParam("课程门类") @RequestParam(value = "category", required = false) String category,
			HttpServletRequest request){
		UserInfo loginInfo = UserInfoUtil.getLoginInfo(UserInfo.class, redisUtil, request);
		if (loginInfo == null) {
			return ResultUtil.data(ResultCode.NOT_LOGIN.getCode(), ResultCode.NOT_LOGIN.getMes(), null);
		}
		Page<Course> page = new Page<>(pageNum, pageSize);
		QueryWrapper<Course> queryWrapper = new QueryWrapper<>();
		if (!StringUtils.isEmpty(title)) {
			queryWrapper.like("title", title);
		}
		
		if (!StringUtils.isEmpty(free)) {
			queryWrapper.eq("free", free);
		}
		if (!StringUtils.isEmpty(type)) {
			queryWrapper.eq("type", type);
		}
		if (!StringUtils.isEmpty(courseType)) {
			queryWrapper.eq("course_type", courseType);
		}
		if (!StringUtils.isEmpty(category)) {
			queryWrapper.eq("category", category);
		}
		queryWrapper.eq("tenant_id", loginInfo.getTenantId());
		queryWrapper.eq("parent_id", "0");
		queryWrapper.orderByDesc("update_time");
		IPage<Course> info = courseMapper.selectPage(page, queryWrapper);
		List<Course> records = info.getRecords();
		for (int i = 0; i < records.size(); i++) {
			records.get(i).getId();
			QueryWrapper<CourseType> queryWrapper1=new QueryWrapper<CourseType>();
			queryWrapper1.eq("course_id", records.get(i).getId());
			List<CourseType> selectList = courseTypeMapper.selectList(queryWrapper1);
			String courseTypeNew="";
			for (CourseType courseType2 : selectList) {
				if(StringUtils.isEmpty(courseTypeNew)) {
					courseTypeNew=courseType2.getPtype()+":"+courseType2.getTypeCode();
				}else {
					courseTypeNew=courseTypeNew+","+courseType2.getPtype()+":"+courseType2.getTypeCode();
				}
			}
			records.get(i).setCourseType(courseTypeNew);
		}
		for (int i=0;i<records.size();i++) {
			if(!StringUtils.isEmpty(records.get(i).getPath())) {
				String data = records.get(i).getPath();
				String newData = data.replace(SystemConfig.ossIp, "");
				String bucketName=newData.substring(0, newData.indexOf("/"));
				String objectName=newData.replace(bucketName, "");
				Result<String> url = ossService.getUrl(bucketName, objectName);
				records.get(i).setPath(url.getData());
			}
		}
		PageInfo<Course> data = PageUtil.data(info.getPages(), info.getCurrent(), info.getTotal(), records);
		return ResultUtil.data(ResultCode.RESULT_SUCCESS.getCode(), null, data);
	}
	
	

	@ApiOperation(value = "添加", notes = "")
	@PostMapping("/course")
	public Result<String> save(@RequestBody Course entity,HttpServletRequest request){
		UserInfo loginInfo = UserInfoUtil.getLoginInfo(UserInfo.class, redisUtil, request);
		if (loginInfo == null) {
			return ResultUtil.data(ResultCode.NOT_LOGIN.getCode(), ResultCode.NOT_LOGIN.getMes(), null);
		}
		int result = 0;
		entity.setParentId("0");
		entity.setIsPackage(1);
	//	entity.setDataPath(entity.getDataPath()!=null?entity.getDataPath().replace(SystemConfig.ossIp, ""):"",false);
	//	entity.setDataImage(entity.getDataImage()!=null?entity.getDataImage().replace(SystemConfig.ossIp, ""):"",false);
	//	entity.setTitleImage(entity.getTitleImage()!=null?entity.getTitleImage().replace(SystemConfig.ossIp, ""):"",false);
	//	entity.setPath(entity.getPath()!=null?entity.getPath().replace(SystemConfig.ossIp, ""):"",false);
		entity.setCreateTime(LocalDateTime.now());
		entity.setUpdateTime(LocalDateTime.now());
		if(StringUtils.isEmpty(entity.getFree())) {
			entity.setFree("1");
		}
		entity.setTenantId(loginInfo.getTenantId());
		result = courseMapper.insert(entity);
		if (result > 0) {
			return ResultUtil.data(ResultCode.RESULT_SUCCESS.getCode(), null, entity.getId());
		} else {
			return ResultUtil.data(ResultCode.RESULT_ERROR.getCode(), ResultCode.RESULT_ERROR.getMes(), null);
		}
	}
	
	
	@ApiOperation(value = "修改", notes = "")
	@PutMapping("/course")
	public Result<String> edit(@RequestBody Course entity,HttpServletRequest request){
		UserInfo loginInfo = UserInfoUtil.getLoginInfo(UserInfo.class, redisUtil, request);
		if (loginInfo == null) {
			return ResultUtil.data(ResultCode.NOT_LOGIN.getCode(), ResultCode.NOT_LOGIN.getMes(), null);
		}
		int result = 0;
	//	entity.setDataPath(entity.getDataPath()!=null?entity.getDataPath().replace(SystemConfig.ossIp, ""):"",false);
	//	entity.setDataImage(entity.getDataImage()!=null?entity.getDataImage().replace(SystemConfig.ossIp, ""):"",false);
	//	entity.setTitleImage(entity.getTitleImage()!=null?entity.getTitleImage().replace(SystemConfig.ossIp, ""):"",false);
	//	entity.setPath(entity.getPath()!=null?entity.getPath().replace(SystemConfig.ossIp, ""):"",false);
		entity.setViews(null);
		entity.setIsPackage(1);
		entity.setTenantId(loginInfo.getTenantId());
		entity.setUpdateTime(LocalDateTime.now());
		result = courseMapper.updateById(entity);
		if (result > 0) {
			return ResultUtil.data(ResultCode.RESULT_SUCCESS.getCode(), null, null);
		} else {
			return ResultUtil.data(ResultCode.RESULT_ERROR.getCode(), ResultCode.RESULT_ERROR.getMes(), null);
		}
	}

	@ApiOperation(value = "删除", notes = "")
	@DeleteMapping("/course/{courseId}")
	public Result<String> del(@PathVariable("courseId") String courseId){
		int result = courseMapper.deleteById(courseId);
		QueryWrapper<CourseType> wrapper=new QueryWrapper<>();
		wrapper.eq("course_id", courseId);
		courseTypeMapper.delete(wrapper);
		if (result > 0) {
			return ResultUtil.data(ResultCode.RESULT_SUCCESS.getCode(), null, null);
		} else {
			return ResultUtil.data(ResultCode.RESULT_ERROR.getCode(), ResultCode.RESULT_ERROR.getMes(), null);
		}
	}
	
	@ApiOperation(value = "获取课程全部视频", notes = "")
	@GetMapping("/course/{courseId}")
	public Result<List<Course>> courselist(@PathVariable("courseId") String courseId,HttpServletRequest request){
		QueryWrapper<Course> queryWrapper = new QueryWrapper<>();
		queryWrapper.eq("parent_id", courseId);
		queryWrapper.orderByAsc("sort");
		List<Course> list = courseMapper.selectList(queryWrapper);
		for (int i=0;i<list.size();i++) {
			if(!StringUtils.isEmpty(list.get(i).getPath())) {
				String data = list.get(i).getPath();
				String newData = data.replace(SystemConfig.ossIp, "");
				String bucketName=newData.substring(0, newData.indexOf("/"));
				String objectName=newData.replace(bucketName, "");
				Result<String> url = ossService.getUrl(bucketName, objectName);
				list.get(i).setPath(url.getData());
			}
		}
		
		return ResultUtil.data(ResultCode.RESULT_SUCCESS.getCode(), null, list);
	}
	
	@ApiOperation(value = "添加课程章节", notes = "")
	@PostMapping("/course/list")
	public Result<String> courseList(@RequestBody List<Course> courseList){
		if (courseList == null || courseList.size() == 0) {
			return ResultUtil.data(ResultCode.RESULT_ERROR.getCode(), "课程列表不能为空", null);
		}
		Course parent = courseMapper.selectById(courseList.get(0).getParentId());
		if(parent==null) {
			return ResultUtil.data(ResultCode.RESULT_ERROR.getCode(), "参数不正确", null);
		}
		QueryWrapper<Course> queryWrapper = new QueryWrapper<>();
		queryWrapper.eq("parent_id", courseList.get(0).getParentId());
		queryWrapper.orderByAsc("sort");
		List<Course> list = courseMapper.selectList(queryWrapper);
		list.addAll(courseList);
		Collections.sort(list, new Comparator<Course>() {
			@Override
			public int compare(Course o1, Course o2) {
				return o1.getTitle().compareTo(o2.getTitle()); // 按价格升序 （降序：02-01）
			}
		});
		int sort = 1;
		boolean isEmpty=false;
		for (Course course : list) {
			if(StringUtils.isEmpty(course.getPath()))
				isEmpty=true;
		}
		if(isEmpty)
			return ResultUtil.data(ResultCode.RESULT_ERROR.getCode(), "章节内容不能为空",null);
		
		 
		for (Course course : list) {
			course.setSort(sort);
			if (StringUtils.isEmpty(course.getId())) {
				course.setCreateTime(LocalDateTime.now());
				course.setTenantId(parent.getTenantId());
				courseMapper.insert(course);
			} else {
				course.setUpdateTime(LocalDateTime.now());
				course.setTenantId(parent.getTenantId());
				courseMapper.updateById(course);
			}
			sort++;
		}
		return ResultUtil.data(ResultCode.RESULT_SUCCESS.getCode(), null, null);
	}
	
	
	
	
	@ApiOperation(value = "获取课程vip价格", notes = "")
	@GetMapping("/course/vipPrice")
	public Result<String> getVipPrice(){
		QueryWrapper<com.zdzx.model.service.base.vo.SystemConfig> queryWrapper=new QueryWrapper<com.zdzx.model.service.base.vo.SystemConfig>();
		queryWrapper.eq("`key`",SystemConfigType.MEMBER_PRICE);
		List<com.zdzx.model.service.base.vo.SystemConfig> list = systemConfigMapper.selectList(queryWrapper);
		if(list!=null&&list.size()>0)
			return ResultUtil.data(ResultCode.RESULT_SUCCESS.getCode(),null, list.get(0).getValue());
		return ResultUtil.data(ResultCode.RESULT_SUCCESS.getCode(), null, null);
	}
	
	@ApiOperation(value = "设置课程vip价格", notes = "")
	@PostMapping("/course/vipPrice/{price}")
	public Result<String> setVipPrice(@PathVariable("price")String price,HttpServletRequest request){
		UserInfo loginInfo = UserInfoUtil.getLoginInfo(UserInfo.class, redisUtil, request);
		if (loginInfo == null) {
			return ResultUtil.data(ResultCode.NOT_LOGIN.getCode(), ResultCode.NOT_LOGIN.getMes(), null);
		}
		if(loginInfo.getAccount().equals("admin")) {
			return ResultUtil.data(ResultCode.RESULT_ERROR.getCode(), "非管理员不可设置！！！", null);
		}
		if(StringUtils.isEmpty(price)) {
			return ResultUtil.data(ResultCode.RESULT_ERROR.getCode(), "vip价格不能为空", null);
		}
		QueryWrapper<com.zdzx.model.service.base.vo.SystemConfig> queryWrapper=new QueryWrapper<com.zdzx.model.service.base.vo.SystemConfig>();
		queryWrapper.eq("`key`",SystemConfigType.MEMBER_PRICE);
		List<com.zdzx.model.service.base.vo.SystemConfig> list = systemConfigMapper.selectList(queryWrapper);
		int rows=0;
		if(list!=null&&list.size()>0) {
			com.zdzx.model.service.base.vo.SystemConfig priceconfig=list.get(0);
			priceconfig.setValue(price);
			rows=systemConfigMapper.updateById(priceconfig);
		}
		return ResultUtil.data(rows>0?ResultCode.RESULT_SUCCESS.getCode():ResultCode.RESULT_ERROR.getCode(), null, null);
	}
	
	
	
	
}
